<?php
namespace app\admin\model;
class Group extends \app\common\model\Base
{
	protected $table = 'admin_group';
	protected $_AllowPreprocess=true;

	use \app\common\model\TreeBase;

	public static function getGroupsList($uid){
		return db('admin_access')->where(['user_id'=>$uid])->order('group_id')->column('group_id');
	}

	public function setRulesAttr($value) {
		if (is_array($value))
			return implode(',',$value);
		else
			return $value;
	}

	public function getRulesAttr($value) {
		if ($value) {
			$val=explode(',',$value);
			foreach ($val as &$v)
				$v=intval($v);
			return $val;
		} else
			return null;
	}

	protected function _before_createData(&$param) {
		if (isset($param['rules'])){
			$v=&$param['rules'];
			if (is_array($v))
				$v=implode(',',$v);
		}
		if ($param['pid']==0 && !in_array(0,$GLOBALS['userInfo']['gids'])){
			return "只有超级管理员有权限创建根用户组";
		}
		return true;
	}

	protected function _before_updateDataById(&$param) {
		if (isset($param['rules'])){
			$v=&$param['rules'];
			if (is_array($v))
				$v=implode(',',$v);
		}
		if ($param['pid']==0 && !in_array(0,$GLOBALS['userInfo']['gids'])){
			return "只有超级管理员有权限修改根用户组";
		}
		return true;
	}

  /**
   * get all the rule's id by the group ids
   *
   * @param <type> $gidskey a key to search cache quickly(you could generate it by gids).
   * @param <type> $gids all the groupsid
   *
   * @return rule ids own by groups(multiple group id).
   */

	public function getRulesList($gidskey,$gids){
		if ($gidskey == "" || !count($gids)) {
			return [];
		}
		$cache = cache("GROUP_ACCESS_".$gidskey);
		if (!$cache) {
			$cache=[];
			if (in_array(0,$gids)) {
				$cache=db('admin_rule')->column('id');
			} else {
				foreach($gids as $gid)
					$cache=array_merge($cache,$this->getRuleList($gid));
				foreach($cache as &$v)
					$v=intval($v);
				$ruleModel=new Rule;
				$cache=array_unique(array_merge($cache,$ruleModel->getAllChild($cache),$ruleModel->getAllParent($cache)));
			}
			cache("GROUP_ACCESS_".$gidskey,$cache,config('cache_param.group_access'),'GROUP_ACCESS');
		}
		return $cache;
	}

	/**
	 * find all the rule,but don't expand it(fill the tree)
	 * @param  [type] $gidskey [description]
	 * @param  [type] $gids    [description]
	 * @return [type]          [description]
	 */
	public function getRulesList_raw($gidskey,$gids){
		if ($gidskey == "" || !count($gids)) {
			return [];
		}
		$cache = cache("GROUP_ACCESS_R_".$gidskey);
		if (!$cache) {
			$cache=[];
			if (in_array(0,$gids)) {
				$cache=db('admin_rule')->column('id');
			} else {
				foreach($gids as $gid)
					$cache=array_merge($cache,$this->getRuleList($gid));
				foreach($cache as &$v)
					$v=intval($v);
				$ruleModel=new Rule;
			}
			cache("GROUP_ACCESS_R_".$gidskey,$cache,config('cache_param.group_access'),'GROUP_ACCESS');
		}
		return $cache;
	}

	protected function getRuleList($gid){
		$rules=db('admin_group')->where(['id'=>$gid])->value('rules');
		$arr = explode(",",$rules);
		return $arr?$arr:[];
	}
}